import 'package:flutter/material.dart';
import '../../util/ApiUtils.dart';
import '../../util/RouteUtils.dart';

class DDImageGrid extends StatefulWidget {
  final int crossCount;
  final List<DDImageInfo> imageList;
  DDImageGrid({this.crossCount = 2, this.imageList});

  @override
  _DDImageGridState createState() => _DDImageGridState();
}

class _DDImageGridState extends State<DDImageGrid> {
  List<DDImageInfo> imageList = [];

  @override
  Widget build(BuildContext context) {
    imageList = widget.imageList;
    List<GridTile> widgetList = [];
    if (imageList != null && imageList.isNotEmpty) {
      widgetList = List.generate(
        imageList.length,
        (int index) => buildGridTile(imageList[index]),
      );
    }

    return new Expanded(
      child: new SafeArea(
        top: false,
        bottom: false,
        child: new GridView.count(
          crossAxisCount: widget.crossCount,
          mainAxisSpacing: 4.0,
          crossAxisSpacing: 4.0,
          padding: const EdgeInsets.all(4.0),
          children: widgetList,
        ),
      ),
    );
  }

  Widget buildGridTile(DDImageInfo imageInfo) {
    String url = ApiUtils.getBigImageUrl(imageInfo.url);
    return GridTile(
      child: new GestureDetector(
        onTap: () {
          RouteUtils.showPhoto(context, imageInfo.title, url);
        },
        child: new Hero(
          tag: imageInfo.title,
          child: Image.network(
            ApiUtils.getSmallImageUrl(imageInfo.smallImageUrl),
            fit: BoxFit.cover,
          ),
        ),
      ),
      footer: new GestureDetector(
        onTap: () {
          RouteUtils.showPhoto(context, imageInfo.title, url);
        },
        child: new GridTileBar(
          backgroundColor: Colors.black45,
          title: getGridTileText(imageInfo.title),
          trailing: new Icon(
            Icons.delete,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  Widget getGridTileText(String text) {
    return new FittedBox(
      fit: BoxFit.scaleDown,
      alignment: Alignment.centerLeft,
      child: new Text(text),
    );
  }
}

///
/// 图片信息模型
///
class DDImageInfo {
  String title;
  String url;
  String smallImageUrl;

  DDImageInfo({
    this.title,
    this.url,
    this.smallImageUrl,
  });
}
